package br.com.infocruz.seam.crm.ejb.facade;

import java.util.Date;

import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.ExcludeDefaultInterceptors;

import org.apache.log4j.Logger;
import org.hibernate.validator.InvalidValue;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import br.com.infocruz.seam.crm.ejb.model.AuditTrail;
import br.com.infocruz.seam.crm.ejb.model.UserAccount;

@Name("auditTrailFacade")
@Stateless
@ExcludeDefaultInterceptors
public class AuditTrailFacadeBean extends AbstractFacade<AuditTrail> implements AuditTrailFacade {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static Logger log = Logger.getLogger(AuditTrailFacadeBean.class);
	
	public AuditTrailFacadeBean() {
		super(AuditTrail.class);
	}

	// @Observer("br.com.infocruz.seam.crm.createAudit")
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void createAudit(String className, String methodName, Date start, Date end, String username) {
		UserAccount userAccount = null;
		if (username != null) {
			userAccount = getUserAccountFacade().findByUsername(username);
		}
		AuditTrail auditTrail = new AuditTrail(className, methodName, start, end, userAccount);
		try {
			create(auditTrail);
		} catch (org.hibernate.validator.InvalidStateException e) {
			InvalidValue[] invalidValues = e.getInvalidValues();
			for (InvalidValue invalidValue : invalidValues) {
				log.info("Invalid Value: " + invalidValue.getPropertyName());
			}
		} catch (Exception e) {
			log.error(e);
			throw new EJBException(e);
		}

	}

	private UserAccountFacade getUserAccountFacade() {
		return (UserAccountFacade)Component.getInstance(UserAccountFacadeBean.class);
	}

}
